#!/bin/bash
# this is the boot-service init script for the puppet resources
#
# openQRM Enterprise developed by openQRM Enterprise GmbH.
#
# All source code and content (c) Copyright 2014, openQRM Enterprise GmbH unless specifically noted otherwise.
#
# This source code is released under the GNU General Public License version 2, unless otherwise agreed with openQRM Enterprise GmbH.
# The latest version of this license can be found here: src/doc/LICENSE.txt
#
# By using this software, you acknowledge having read this license and agree to be bound thereby.
#
#           http://openqrm-enterprise.com
#
# Copyright 2014, openQRM Enterprise GmbH <info@openqrm-enterprise.com>
#
OPENQRM_SERVER_BASE_DIR=$(pushd $(dirname $0)/../../../../.. > /dev/null; echo $PWD; popd > /dev/null)
# for including the package functions
export OPENQRM_SOURCE_DIR="$OPENQRM_SERVER_BASE_DIR/openqrm/"
. $OPENQRM_SERVER_BASE_DIR/openqrm/include/openqrm-functions
. $OPENQRM_SERVER_BASE_DIR/openqrm/include/openqrm-package-functions
. $OPENQRM_SERVER_BASE_DIR/openqrm/plugins/puppet/include/openqrm-plugin-puppet-functions
. $OPENQRM_RESOURCE_PARAMETER_FILE
OPENQRM_SERVER_IP=$resource_openqrmserver
LOCKFILE=/var/lock/openqrm-puppet

# do not run on idle resources
if [ "$resource_image" == "idle" ]; then
	exit 0
fi

# set the hostname early 
hostname $appliance_name

# also do not run before the real init of the rootfs
# if we have this file /etc/initrd-devices.conf we are still in the initrd
if [ -f /etc/initrd-devices.conf ]; then
	exit 0
fi
if [ -f /etc/debian_version ]; then
	echo "$appliance_name" > /etc/hostname
elif [ -f /etc/redhat-release ]; then
	sed -i -e "s#HOSTNAME=.*#HOSTNAME=$appliance_name#g" /etc/sysconfig/network
elif [ -f /etc/SuSE-release ]; then
	echo "$appliance_name" > /etc/HOSTNAME
fi


function puppet_start() {
	if [ -e "$LOCKFILE" ]; then
		echo "puppet already started for the first time"
	else
		touch $LOCKFILE
		# clean up eventual left-overs, be sure we get signed
		rm -rf /etc/puppet/ssl/* /var/lib/puppet/ssl/* /var/lib/puppet/state/*
		openqrm_chkconfig del puppet
	fi

	echo "Starting the openQRM puppet-plugin"
	if ! which puppet 1>/dev/null 2>&1; then
		export FORCE_INSTALL=true
		openqrm_install_os_dependency puppet
	fi
	puppet_stop 1>/dev/null 2>&1
	start_puppet
}


function puppet_stop() {
	echo "Stopping the openQRM puppet-plugin"
	stop_puppet
}





case "$1" in
	start)
		puppet_start
		;;
	stop)
		puppet_stop
		;;
	restart)
		puppet_stop
		sleep 1
		puppet_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1

esac
exit $?




